package com.example.qwen02.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@CrossOrigin
@RequestMapping("/bg")
public class BackGroundController {
    @PostMapping("/upload")
    public Map<String, Object> updatePhoto(MultipartFile photo) throws IOException {
        if (photo == null) {
            System.out.println("上传失败，image为空！");
            return null;
        }
        photo.transferTo(new File(" E:\\Vue\\photos\\" + photo.getOriginalFilename()));
        Map<String, Object> map = new HashMap<>();
        map.put("url", "/bg/photos/" + photo.getOriginalFilename());
        System.out.println("上传成功");
        return map;
    }

    /**
     * Post请求
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping("/askStyleChange")
    public Map<String, Object> askStyleChange(String base_url, String ref_url,String prompt) throws Exception {
        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建HttpPost对象，指定URL
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/background-generation/generation/";
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头，包括Content-Type为application/json
        httpPost.setHeader("X-DashScope-Async", "enable");
        httpPost.setHeader("Authorization", "Bearer"+System.getenv("DASHSCOPE_API_KEY"));
        httpPost.setHeader("Content-type", "application/json");



        // JSON参数
        String jsonParam = "{\n" +
                "    \"model\": \"wanx-background-generation-v2\",\n" +
                "    \"input\": {\n" +
                "        \"base_image_url\": \""+base_url+"\",\n" +
                "        \"ref_image_url\": \""+ref_url+ "\",\n" +
                "        \"ref_prompt\": \""+ prompt +"\",\n" +
                "        \"reference_edge\": {\n" +
                "            \"foreground_edge\": [\n" +
                "                \"https://vision-poster.oss-cn-shanghai.aliyuncs.com/lllcho.lc/data/test_data/images/huaban_soft_edge/6cdd13941cef1b11d885aea1717b983ae566b8efc9094-vcsvxa_fw658webp.png\"\n" +
                "            ]\n" +
                "        }\n" +
                "    },\n" +
                "    \"parameters\": {\n" +
                "        \"n\": 4,\n" +
                "        \"noise_level\": 300,\n" +
                "        \"ref_prompt_weight\": 0.5,\n" +
                "        \"scene_type\": \"GENERAL\"\n" +
                "    }\n" +
                "}";

        // 将JSON字符串转换为HttpEntity对象并设置到HttpPost中
        httpPost.setEntity(new StringEntity(jsonParam));

        try {
            // 执行HTTP POST请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 如果请求成功，读取响应实体
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            response.close();

            Map<String, Object> map = new HashMap<>();
            // result是json格式,我们提取出它的结果
            // 解析整个JSON字符串为一个JSONObject
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.containsKey("output")) {
                // 从JSONObject中获取名为"output"的子对象
                JSONObject outputObject = jsonObject.getJSONObject("output");
                // 从outputObject中提取task_id字段的值
                String taskId = outputObject.getString("task_id");
                map.put("state", "success");
                map.put("task_id", taskId);
            } else {
                map.put("state", "error");
                map.put("error", jsonObject.getString("message"));
            }
            System.out.println("post-Response: " + result);
            return map;
        } finally {
            httpClient.close();
        }
    }

    /**
     * 取图片
     * @param task_id
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/getImage",produces = "application/json;charset=utf-8")
    public String getImage(String task_id) throws IOException {
        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建HttpGet对象，指定URL
        String url = "https://dashscope.aliyuncs.com/api/v1/tasks/"+task_id;
//        HttpPost httpPost = new HttpPost(url);
        HttpGet httpGet = new HttpGet(url);

        // 设置请求头，包括Content-Type为application/json
        httpGet.setHeader("Authorization", "Bearer"+System.getenv("DASHSCOPE_API_KEY"));

        try {
            // 执行HTTP POST请求
            CloseableHttpResponse response = httpClient.execute(httpGet);

            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            System.out.println("Response: " + result);
            response.close();
            return  result;
        } finally {
            httpClient.close();
        }
    }
}
